package com.software.loginregister.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;


public class LocationUtil {
    private static final int PERMISSION_REQUEST_CODE = 1001;
    private LocationManager locationManager;
    private Context context;
    private LocationListener locationListener;

    public LocationUtil(Context context) {
        this.context = context;
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    }

    public interface LocationCallback {
        void onLocationReceived(Location location);
        void onLocationFailed(String error);
    }

    @SuppressLint("MissingPermission")
    public void getCurrentLocation(LocationCallback callback) {
        // 检查权限
        if (!checkPermissions()) {
            callback.onLocationFailed("需要定位权限");
            return;
        }

        // 检查GPS是否开启
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            callback.onLocationFailed("请开启GPS");
            return;
        }

        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                callback.onLocationReceived(location);
                locationManager.removeUpdates(locationListener);
            }

            @Override
            public void onProviderDisabled(@NonNull String provider) {
                callback.onLocationFailed("定位服务已关闭");
            }

            @Override
            public void onProviderEnabled(@NonNull String provider) {}

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}
        };

        // 请求位置更新
        locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                1000, // 最小时间间隔
                10,   // 最小距离变化
                locationListener
        );
    }

    private boolean checkPermissions() {
        return ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(context,
                Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
    }
}